<template>
  <el-container class="dashboard-container">
    <!-- 顶部导航 -->
    <el-header class="header">
      <div class="header-left">
        <el-button 
          type="text" 
          @click="toggleSidebar"
          :style="{ marginRight: isCollapsed ? '0' : '10px' }"
        >
          <i class="el-icon-s-fold"></i>
        </el-button>
        <span class="title">校园绿植领养系统</span>
      </div>
      <div class="header-right">
        <el-dropdown @command="handleCommand">
          <span class="el-dropdown-link">
            {{ userInfo.username }} <i class="el-icon-caret-bottom"></i>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">个人信息</el-dropdown-item>
              <el-dropdown-item command="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-header>

    <!-- 侧边栏 -->
    <el-aside :width="isCollapsed ? '64px' : '200px'" class="sidebar">
      <el-menu 
        :default-active="activeMenu" 
        class="el-menu-vertical"
        :collapse="isCollapsed"
        @open="handleOpen"
        @close="handleClose"
      >
        <el-menu-item index="dashboard">
          <i class="el-icon-s-home"></i>
          <span slot="title">仪表盘</span>
        </el-menu-item>
        <el-submenu index="plant">
          <template #title>
            <i class="el-icon-tree"></i>
            <span>绿植管理</span>
          </template>
          <el-menu-item index="plant/list">绿植列表</el-menu-item>
          <el-menu-item index="plant/category">绿植分类</el-menu-item>
          <el-menu-item index="plant/add">添加绿植</el-menu-item>
        </el-submenu>
        <el-submenu index="user">
          <template #title>
            <i class="el-icon-user"></i>
            <span>用户管理</span>
          </template>
          <el-menu-item index="user/list">用户列表</el-menu-item>
          <el-menu-item index="user/adoption">领养记录</el-menu-item>
        </el-submenu>
        <el-submenu index="system">
          <template #title>
            <i class="el-icon-s-tools"></i>
            <span>系统设置</span>
          </template>
          <el-menu-item index="system/config">系统配置</el-menu-item>
          <el-menu-item index="system/log">操作日志</el-menu-item>
        </el-submenu>
      </el-menu>
    </el-aside>

    <!-- 主内容区 -->
    <el-main class="main-content">
      <el-card class="stat-card">
        <div class="stat-title">数据概览</div>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="stat-item">
              <div class="item-title">总用户数</div>
              <div class="item-count">{{ totalUsers }}</div>
              <div class="item-trend">
                <i class="el-icon-arrow-up"></i>
                <span>12.5%</span>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-item">
              <div class="item-title">绿植总数</div>
              <div class="item-count">{{ totalPlants }}</div>
              <div class="item-trend">
                <i class="el-icon-arrow-up"></i>
                <span>8.2%</span>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-item">
              <div class="item-title">领养次数</div>
              <div class="item-count">{{ totalAdoptions }}</div>
              <div class="item-trend">
                <i class="el-icon-arrow-up"></i>
                <span>15.3%</span>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-item">
              <div class="item-title">待审核申请</div>
              <div class="item-count">{{ pendingApplications }}</div>
              <div class="item-trend">
                <i class="el-icon-arrow-down"></i>
                <span>3.1%</span>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-card>

      <!-- 图表区域 -->
      <el-row :gutter="20" class="mt-20">
        <el-col :span="12">
          <el-card class="chart-card">
            <div class="chart-title">领养趋势</div>
            <div ref="adoptionChartRef" class="chart-container"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card">
            <div class="chart-title">绿植分类分布</div>
            <div ref="categoryChartRef" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 最近领养记录 -->
      <el-card class="mt-20">
        <div class="record-title">最近领养记录</div>
        <el-table 
          :data="recentAdoptions" 
          stripe 
          border
          size="small"
        >
          <el-table-column prop="username" label="用户名"></el-table-column>
          <el-table-column prop="plantName" label="绿植名称"></el-table-column>
          <el-table-column prop="adoptionTime" label="领养时间"></el-table-column>
          <el-table-column prop="status" label="状态">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useUserStore } from '@/store/user';
import { getDashboardData } from '@/api/dashboard';
import * as echarts from 'echarts';

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

const isCollapsed = ref(false);
const activeMenu = computed(() => route.path);
const userInfo = computed(() => userStore.userInfo);

const totalUsers = ref(0);
const totalPlants = ref(0);
const totalAdoptions = ref(0);
const pendingApplications = ref(0);
const recentAdoptions = ref([]);

const adoptionChartRef = ref(null);
const categoryChartRef = ref(null);

const toggleSidebar = () => {
  isCollapsed.value = !isCollapsed.value;
};

const handleCommand = (command) => {
  if (command === 'logout') {
    userStore.logout();
    router.push('/login');
  } else if (command === 'profile') {
    router.push('/user/profile');
  }
};

const getStatusType = (status) => {
  switch (status) {
    case '已领养': return 'success';
    case '待审核': return 'warning';
    case '已归还': return 'info';
    case '已拒绝': return 'danger';
    default: return 'info';
  }
};

const initAdoptionChart = () => {
  const chart = echarts.init(adoptionChartRef.value);
  
  const options = {
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: [120, 132, 101, 134, 90, 230],
      type: 'line',
      smooth: true
    }]
  };
  
  chart.setOption(options);
};

const initCategoryChart = () => {
  const chart = echarts.init(categoryChartRef.value);
  
  const options = {
    series: [{
      type: 'pie',
      radius: '50%',
      data: [
        { value: 335, name: '多肉植物' },
        { value: 310, name: '观叶植物' },
        { value: 234, name: '开花植物' },
        { value: 135, name: '仙人掌' },
        { value: 1548, name: '其他' }
      ]
    }]
  };
  
  chart.setOption(options);
};

onMounted(async () => {
  try {
    const res = await getDashboardData();
    if (res.code === 200) {
      totalUsers.value = res.data.totalUsers;
      totalPlants.value = res.data.totalPlants;
      totalAdoptions.value = res.data.totalAdoptions;
      pendingApplications.value = res.data.pendingApplications;
      recentAdoptions.value = res.data.recentAdoptions;
    }
  } catch (error) {
    ElMessage.error('获取数据失败');
  }

  initAdoptionChart();
  initCategoryChart();
});
</script>

<style scoped>
.dashboard-container {
  height: 100vh;
}

.header {
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.header-left {
  display: flex;
  align-items: center;
}

.title {
  font-size: 20px;
  font-weight: 500;
  color: #333;
}

.sidebar {
  background-color: #f0f2f5;
}

.main-content {
  padding: 20px;
  background-color: #f8f9fa;
}

.stat-card {
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
  padding: 20px;
}

.item-title {
  font-size: 14px;
  color: #606266;
}

.item-count {
  font-size: 28px;
  font-weight: 600;
  margin: 10px 0;
}

.item-trend {
  font-size: 12px;
  color: #909399;
}

.chart-card {
  height: 300px;
}

.chart-title {
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: 500;
}

.chart-container {
  width: 100%;
  height: 240px;
}

.record-title {
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: 500;
}

.mt-20 {
  margin-top: 20px;
}
</style>